package com.java.test.algorithm;

/**
 * Input: 19
 Output: true
 Explanation:
 12 + 92 = 82
 82 + 22 = 68
 62 + 82 = 100
 12 + 02 + 02 = 1
 */
public class HappyNumber {
    public static void main(String[] args) {
        System.out.println(HappyNumber.isHappy(19));
//        System.out.println(HappyNumber.isHappy(18));
    }

    static boolean  isHappy(int n) {
        // Write your code here
        int sum = n;

        while(true)
        {
            sum = numSum(sum);
            /**
             * 16, 37, 58, 89, 145, 42, 20, 4
             这几个数字是一个循环圈
             */
            if(sum == 4)
            {
                break;
            }

            if(sum == 1)
            {
                return true;
            }
        }

        return false;
    }

    static int numSum(int n)
    {
        int sum = 0;
        int x;
        while(n != 0)
        {
            x = n % 10;
            n = n /10;
            sum += x * x;
        }

        return sum;
    }

}
